---
title: Caching
description: >-
  This guide will cover all sorts of topics related to Spree application
  performance
---

Caching is a great way to improve the performance of your Spree application. In all modern web applications, usually the most time consuming operations are database queries and rendering templates. Caching allows you to store the results of these operations in memory and serve them from there.

We recommend using a distributed cache storage engine such as Memcached, Valkey or Redis. Spree Starter uses Redis by default.

## Setting up Redis (or Valkey) as a cache storage engine

<Info>
If you're using Spree Starter, you don't need to do anything as it's already pre-configured for you.
</Info>

Firstly add `redis` gem to your project

```bash
bundle add redis
```

Now, you will need to change the `config/environments/production.rb` from:

```ruby
# config.cache_store = :mem_cache_store
```

to:

```ruby
if ENV['REDIS_CACHE_URL'].present?
  cache_servers = ENV['REDIS_CACHE_URL'].split(',') # if multiple instances are provided
  config.cache_store = :redis_cache_store, {
    url: cache_servers,
    connect_timeout:    30,  # Defaults to 1 second
    read_timeout:       0.2, # Defaults to 1 second
    write_timeout:      0.2, # Defaults to 1 second
    reconnect_attempts: 2,   # Defaults to 1
  }
end
```

For more advanced configuration options, please refer to the [Spree Starter repository](https://github.com/spree/spree_starter/blob/main/config/environments/production.rb#L72).

## Testing locally

To enable caching in the development environment please type in your project directory:

```bash
bin/rails dev cache
```

You will need to restart your webserver after this.

## API cache

<Info>
Changing Spree API cache is only required for applications heavily using the API. The default configuration is already optimized for the most common use cases.
</Info>

Additionally Spree API has a built-in caching mechanism. It's enabled by default and you don't need to do anything to enable it. You can however tweak it to your needs.

The default cache TTL is 1 hour. You can change it by setting `Spree::Api::Config[:api_v2_serializers_cache_ttl]` in `config/initializers/spree.rb`, eg.

```ruby
Spree::Api::Config[:api_v2_serializers_cache_ttl] = 3600 # 1 hour
```

This is the setting for caching individual objects (serializers), eg. Products, Orders, etc.

We also have a setting for caching collections of objects (serializers), eg. Product listings. It's `Spree::Api::Config[:api_v2_collection_cache_ttl]`.

```ruby
Spree::Api::Config[:api_v2_collection_cache_ttl] = 3600 # 1 hour
```

After modifying the settings, you will need to restart your webserver.
